/*
 * Copyright (C) 2011 Johan Kannala
 *
 * Licensed under the MIT License. You can find a copy of the License at in the
 * license.txt file.
 */
package com.joppe.vocabtutor;

import android.app.*;
import android.content.*;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.*;
import android.view.*;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class ListBooksActivity extends LoggedActivity {
	private static final int CREATE_QUIZ = 0;
	private static final int ADD_BOOK = 1;
	private static final int DELETE_BOOKS = 2;
	
	private static final int DELETE_BOOKS_DLG = 1;
	
	private VocabTutor mApplication = null;
	private BookClickListener mBookClickListener = new BookClickListener();
	private Cursor mBooksCursor = null;

	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApplication = (VocabTutor) this.getApplication();
        setContentView(R.layout.book_list);
        ListView bookList = (ListView) findViewById(R.id.book_list);
        bookList.setOnItemClickListener(mBookClickListener);
        bookList.setOnItemLongClickListener(mBookClickListener);
        SQLiteDatabase db = mApplication.getDataHelper().getReadableDatabase();
        mBooksCursor = db.query("books left join chapters on books._id = chapters.book_fk left join words on chapters._id = words.chapter_fk",
                        new String[] { "books._id as _id", "books.title",
                                "count(distinct chapters._id)",
                                "count(words._id)" }, null, null, "books._id",
                        null, null);
        BookListCursorListAdapter la = new BookListCursorListAdapter(this,
                mBooksCursor);
        bookList.setAdapter(la);
    }
	
	@Override
	public void onResume() {
	    super.onResume();
	    mBooksCursor.requery();
	}
	
    @Override
    public void onStop() {
        super.onStop();
        mBooksCursor.deactivate();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        mBooksCursor.close();
        mBooksCursor = null;
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, CREATE_QUIZ, Menu.NONE, "Generate new quiz");
		menu.add(Menu.NONE, ADD_BOOK, Menu.NONE, "Add new book");
		menu.add(Menu.NONE, DELETE_BOOKS, Menu.NONE, "Delete books");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case CREATE_QUIZ:
			ListView bookList = (ListView) findViewById(R.id.book_list);
			SparseBooleanArray selection = bookList.getCheckedItemPositions();
			long[] selectedIds = bookList.getCheckItemIds();
			return true;
		case ADD_BOOK:
		    Intent i = new Intent(this, CreateBookActivity.class);
		    startActivity(i);
		    return true;
		case DELETE_BOOKS:
			showDialog(DELETE_BOOKS_DLG);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DELETE_BOOKS_DLG: {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Delete books");
			builder.setMessage("Temp message");
			builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					ListView bookList = (ListView) findViewById(R.id.book_list);
					long[] selectedIds = bookList.getCheckItemIds();
					String selectString = VocabTutor.toCommaSeparatedString(selectedIds);
					SQLiteDatabase db = null;
                    try {
                        db = mApplication.getDataHelper().getWritableDatabase();
                        db.delete("books", "_id in " + selectString, null);
                        mBooksCursor.requery();
                    }
                    catch (Throwable t) {
                        t.printStackTrace();
                    }
				}
			});
			builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Log.i("event_notification", "Book deletion cancelled");
				}
			});
			return builder.create();
		}
		}
		return super.onCreateDialog(id);
	}
	
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case DELETE_BOOKS_DLG: {
			AlertDialog ad = (AlertDialog) dialog;
			ad.setMessage("Are you sure you want to delete the following books?");
			ListView bookList = (ListView) findViewById(R.id.book_list);
			long[] selectedIds = bookList.getCheckItemIds();
			String selectString = VocabTutor.toCommaSeparatedString(selectedIds);
			SQLiteDatabase db = null;
			Cursor c = null;
			try {
				db = mApplication.getDataHelper().getWritableDatabase();
				c = db.query("books", new String[] {"title"},
						"_id in " + selectString, null, null, null, null);
				StringBuilder buf = new StringBuilder("Are you sure you want to delete the following books?");
				while (c.moveToNext()) {
					buf.append('\n').append(c.getString(0));
				}
				ad.setMessage(buf.toString());
			}
			catch (Throwable t) {
				t.printStackTrace();
			}
			finally {
			    if (c != null)
			        c.close();
			}
			break;
		}
		}
		super.onPrepareDialog(id, dialog);
	}
	
	private class BookClickListener implements OnItemClickListener,
			OnItemLongClickListener {
		@Override
		public void onItemClick(AdapterView<?> booksList, View item,
				int position, long rowid) {
			Log.i("selection_info", "Book clicked: "
					+ booksList.getItemAtPosition(position));
		}

		@Override
		public boolean onItemLongClick(AdapterView<?> booksList, View item,
				int position, long rowid) {
			Log.i("selection_info", "Book long-clicked: "
					+ booksList.getItemAtPosition(position));
			Intent i = new Intent(ListBooksActivity.this,
					ListChaptersActivity.class);
			i.putExtra("book_id", rowid);
			startActivity(i);
			return false;
		}
	}
}